<template>
  <div v-loading="loading">
    <el-row type="flex" justify="space-between">
      <el-col :span="6">
        <el-row type="flex" justify="space-between">
          <el-col :span="6">
            <div class="current">
              <span v-if="isNow" class="gl_fs_14">本月</span>
              <span v-else class="gl_fs_14">非本月</span>
            </div>
          </el-col>
          <el-col :span="16" align="right"><div class="class_name gl_ellipsis">{{ className }}</div></el-col>
        </el-row>
      </el-col>
      <el-col :span="8">
        <div class="date">
          <el-button size="mini" class="left_right_btn" type="text" icon="el-icon-arrow-left" @click="toPrev(currentYear, currentMonth)" />
          <span class="gl_dis_ib gl_middle">{{ currentMonthDate }}</span>
          <el-button size="mini" class="left_right_btn" type="text" @click="toNext(currentYear, currentMonth)">
            <i class="el-icon-arrow-right el-icon--right" />
          </el-button>
        </div>
      </el-col>
      <el-col :span="6" class="gl_fs_14" align="right">
        <span class="type" :class="[ typeTimeTable == 'day' ? 'type_active': '' ]" @click="changeType('day')">日</span>
        <span class="type" :class="[ typeTimeTable == 'week' ? 'type_active': '' ]" @click="changeType('week')">周</span>
        <span class="type" :class="[ typeTimeTable == 'month' ? 'type_active': '' ]" @click="changeType('month')">月</span>
      </el-col>
    </el-row>
    <div class="gl_mt_5" style="height: 830px">
      <div class="timetable_month">
        <!-- 星期 -->
        <ul class="weekdays">
          <li v-for="tag in weekTag" :key="tag.en">
            <p>{{ tag.en }}</p>
            <p>{{ tag.zh }}</p>
          </li>
        </ul>
        <!-- 日期 -->
        <div>
          <ul v-for="(week, wndex) in dayList" :key="wndex" class="days">
            <li v-for="(day, index) in week" :key="index">
              <!-- <li v-for="(day, index) in week" :key="index" @click="pick(day, index + wndex * 7)"> -->
              <!--本月-->
              <div :class="[ day.getMonth()+1 != currentMonth ? 'other_month': '' ]">
                <!-- <div :class="[ day.getMonth()+1 != currentMonth ? 'other_month': '', {'selected':isSelected[index + wndex*7]} ]"> -->
                <!--每天，今天样式为active-->
                <span :class="[ day.getFullYear() == new Date().getFullYear() && day.getMonth() == new Date().getMonth() && day.getDate() == new Date().getDate() && day.getMonth()+1 == currentMonth ? 'active': 'no_active' ]">{{ day.getDate() }}</span>
              </div>
              <div v-if="day.getMonth()+1 == currentMonth" class="bottom_box">
                <template v-if="classList[day.getDate()] && classList[day.getDate()].length > 3">
                  <div
                    v-for="(ctem, cndex) in classList[day.getDate()]"
                    :key="cndex"
                    class="gl_dis_ib class_td"
                    :style="{ width: '24px', background: ctem.courseScheduleColor }"
                  >
                    <Hover :is-order-page="isOrderPage" :class-name="ctem.className" :data="ctem" :week="String(index + 1)" @edit="edit" @remove="remove">
                      <div slot="content" style="height: 80px" @click="toClassTimetable(ctem)">
                        <span>{{ classId ? formatClass(ctem.courseName) : formatClass(ctem.className) }}</span>
                      </div>
                    </Hover>
                  </div>
                </template>
                <template v-else>
                  <div
                    v-for="(ctem, cndex) in classList[day.getDate()]"
                    :key="cndex"
                    class="gl_dis_ib class_td"
                    :style="{ width: 100 / classList[day.getDate()].length + '%', background: ctem.courseScheduleColor }"
                  >
                    <Hover :is-order-page="isOrderPage" :class-name="ctem.className" :data="ctem" :week="String(index + 1)" :code="'get'" @edit="edit" @remove="remove">
                      <div slot="content" @click="toClassTimetable(ctem)">
                        <span>{{ classId ? ctem.courseName : ctem.className }}</span>
                      </div>
                    </Hover>
                  </div>
                </template>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <CreateDialog ref="createDialog" @refresh="refresh" />
  </div>
</template>

<script>
import Hover from '../hover.vue';
import CreateDialog from '@/components/Class/createDialog.vue';
import { FormatDate } from '@/lib';
import {
  api_GET_ClubCourseSchedule, // 获取课表
  api_GET_ClubCourseScheduleCanBeReservedCourseSchedules, // 预约
  api_DELETE_ClubCourseScheduleId
} from '@/extend/api/hallswaggerApi/app.js';
import {
  Api_GET_ClubCourseScheduleQO
} from '@/lib/form/hall/swaggerForm.js';
export default {
  components: {
    Hover,
    CreateDialog
  },
  props: {
    typeTimeTable: {
      type: String,
      default: 'week'
    },
    searchForm: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      loading: false,
      form: new Api_GET_ClubCourseScheduleQO(),
      isOrderPage: false, // 是否是预约管理页面
      className: '',
      classId: '',
      weekTag: [
        { en: 'MON', zh: '周一' },
        { en: 'TUE', zh: '周二' },
        { en: 'WED', zh: '周三' },
        { en: 'THU', zh: '周四' },
        { en: 'FRI', zh: '周五' },
        { en: 'SAT', zh: '周六' },
        { en: 'SUN', zh: '周日' }
      ],
      classList: {},
      isNow: true, // 是否为本天、本周、本月
      firstDate: '', // 当前月的第一天
      endDate: '',
      nowMonthDate: '', // 今天的年月
      currentMonthDate: '', // 当前的年月
      currentYear: 1970, // 当前年份
      currentMonth: 1, // 当前月份
      currentDay: 1, // 当前日期
      currentWeek: 1, // 当前星期

      firstDateWeek: 1, // 当前月第一天是周几
      weeks: [], // 当前月的每周
      dayList: [] // 当前月的日历 7*6 42天
      // selectDay: '', // 选中的日期
      // isSelected: [], // 当前月中选中的日期，用于做样式区别
      // selectIndex: ''
    };
  },
  watch: {
    typeTimeTable: {
      immediate: true,
      handler(val) {
        if (val === 'month') {
          this.className = this.$route.params.classId ? this.$route.query.name : '';
          this.classId = this.$route.params.classId || '';
          this.getDayList(null);
          // 今天的年月
          const date = new Date();
          const month = date.getMonth() + 1;
          this.nowMonthDate = date.getFullYear() + '年' + month + '月';
        }
      }
    },
    searchForm: {
      immediate: true,
      deep: true,
      handler(val) {
        const first = new Date(this.firstDate); // 当前月第一天
        this.getDayList(this.formatDate(first.getFullYear(), first.getMonth() + 1, 1));
      }
    },
    // 监测当前月是否为本月
    currentMonthDate: {
      immediate: true,
      handler(val) {
        this.isNow = val === this.nowMonthDate;
      }
    }
  },
  created() {
    // 是否是预约页面
    if (this.$route.path.indexOf('/selectAppointmentClass') > 0) {
      this.isOrderPage = true;
    }
  },
  methods: {
    changeType(code) {
      this.$emit('changeType', code);
    },
    getDayList(current) {
      let date = '';
      if (current) {
        date = new Date(current);
      } else {
        date = new Date();
      }
      this.dayList = [];
      this.currentDay = date.getDate(); // 当前日期 几号
      this.currentYear = date.getFullYear(); // 当前年份
      this.currentMonth = date.getMonth() + 1; // 当前月份
      this.currentWeek = date.getDay(); // 1...6,0   // 今天是星期几
      this.currentMonthDate = this.currentYear + '年' + this.currentMonth + '月';

      // 当前月的第一天是星期几
      date.setDate(1);
      this.firstDateWeek = date.getDay(); // 1...6,0
      if (this.firstDateWeek === 0) { // 0为周日
        this.firstDateWeek = 7;
      }
      this.firstDate = this.formatDate(this.currentYear, this.currentMonth, 1);// 当前月第一天 年-月-日
      this.endDate = new Date(this.currentYear, this.currentMonth, 0);
      this.endDate = FormatDate(this.endDate, 'yyyy-MM-dd');
      this.weeks.length = 0;

      // 当前月第一天是周日，放在第一行第7个位置，前面6个
      // 如果1号不是星期天
      for (let i = this.firstDateWeek - 1; i >= 0; i -= 1) {
        const d = new Date(this.firstDate);
        d.setDate(d.getDate() - i);
        this.weeks.push(d); // 1号放进月的第一周里(包括1号之前，上个月末的几天)
      }
      // 如果1号是星期天为 7 的情况， 为7天就直接放在dayList里
      if (this.weeks.length % 7 === 0) {
        this.dayList.push(this.weeks); // 当前月的第一周放进月里
        this.weeks = [];
      }

      for (let j = 1; j <= 42 - this.firstDateWeek; j++) {
        const d = new Date(this.firstDate);
        d.setDate(d.getDate() + j);
        this.weeks.push(d); // 一个 weeks 就是一行7天  dayList 就是个数组，里面有六个weeks
        if (this.weeks.length % 7 === 0) {
          this.dayList.push(this.weeks); // 每满一周，放进月里
          this.weeks = []; // 清空重新存放下一周
        }
      }
      if (this.$route.path.indexOf('/selectAppointmentClass') > 0) {
        this.isOrderPage = true;
        // 如果是预约页面，则走另一个接口
        this.getOrderData();
      } else {
        this.isOrderPage = false;
        // 获取数据
        this.getData(this.classId);
      }
    },
    // 当前页面为课表时
    getData(id) {
      var that = this;
      that.loading = true;
      if (this.$route.path.indexOf('/trialclass') > 0) {
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var day = now.getDate();
        console.log(year, month, day);
        that.form.StartTime = year + '-' + month + '-' + day;
      } else {
        that.form.StartTime = that.firstDate;
      }

      that.form.EndTime = that.endDate;
      that.form.CourseName = that.searchForm.CourseName;
      that.form.TeachingModeCode = that.searchForm.TeachingModeCode;
      that.form.CoachName = that.searchForm.CoachName;
      that.form.IsFinished = null;
      that.form.IncludeClass = true;
      that.form.IncludeCourse = true;
      that.form.IncludeCoach = true;
      that.form.IncludeClassroom = true;
      that.form.IncludeMessageTemplate = true;
      that.form.IncludeDeleted = true;
      that.form.ClassId = id || null;
      that.form.SkipCount = null;
      that.form.MaxResultCount = null;
      const time = that.form.StartTime + '~' + that.form.EndTime;
      that.$emit('getTime', time);
      api_GET_ClubCourseSchedule(that.form).then(res => {
        that.handlerData(res.items);
        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 当前页面为预约时
    getOrderData() {
      var that = this;
      that.loading = true;
      const form = {
        CourseName: that.searchForm.CourseName,
        TeachingModeCode: that.searchForm.TeachingModeCode,
        StudentId: that.$route.query.studentId,
        StartTime: that.firstDate,
        EndTime: that.endDate
      };
      api_GET_ClubCourseScheduleCanBeReservedCourseSchedules(form).then(res => {
        that.handlerData(res);
        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    handlerData(array) {
      this.classList = {};
      for (let i = 0; i < array.length; i++) {
        const item = array[i];
        let day = FormatDate(item.courseDate, 'dd');
        day = day < 10 ? day.substr(1, 1) : day;
        if (this.classList[day]) {
          this.classList[day].push(item);
        } else {
          this.$set(this.classList, day, []);
          this.classList[day].push(item);
        }
      }
    },
    // 去往班课表
    toClassTimetable(row) {
      if (this.$route.path.indexOf('/trialclass') > 0) {
        return;
      }
      if (!this.isOrderPage) {
        const params = {
          classId: row.classId
        };
        this.$router.push({
          name: 'ClassTimetable',
          params: params,
          query: {
            name: row.className
          }
        });
      }
    },
    // 上一月 传入当前年份和月份
    toPrev(year, month) {
      this.dayList = [];
      // this.isSelected = [];
      const first = new Date(this.formatDate(year, month, 1)); // 当前月第一天
      first.setDate(0); // 将某一天设置为上个月的最后一天
      this.getDayList(this.formatDate(first.getFullYear(), first.getMonth() + 1, 1));
    },
    // 下一月 传入当前年份和月份
    toNext(year, month) {
      this.dayList = [];
      // this.isSelected = [];
      const first = new Date(this.formatDate(year, month, 1)); // 当前月第一天
      first.setDate(42);
      this.getDayList(this.formatDate(first.getFullYear(), first.getMonth() + 1, 1));
    },
    // 当前选择日期
    // pick(date, index) {
    //   this.selectIndex = index;
    //   this.isSelected = [];
    //   this.selectDay = this.formatDate(date.getFullYear(), date.getMonth() + 1, date.getDate());
    //   for (let i = 0; i < 42; i++) {
    //     if (index === i) {
    //       this.isSelected.push(true);
    //       continue;
    //     }
    //     this.isSelected.push(false);
    //   }
    // },
    // 格式化日期 yyyy-MM-dd
    formatDate(year, month, day) {
      const y = year;
      let m = month;
      if (m < 10) m = `0${m}`;
      let d = day;
      if (d < 10) d = `0${d}`;
      return `${y}-${m}-${d}`;
    },
    // 删除
    remove(data) {
      var that = this;
      that.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api_DELETE_ClubCourseScheduleId(data.id).then(res => {
          that.getData(that.classId);
          that.$message({ type: 'success', message: '删除成功!' });
        }).catch(error => {
          that.$message({ type: 'error', message: '删除失败 ' + error.error.message });
        });
      }).catch(() => {});
    },
    refresh() {
      this.getData(this.classId);
    },
    // 编辑
    edit(data) {
      this.$refs.createDialog.open('编辑', data);
    },
    formatClass(str) {
      if (str.length > 5) {
        return str.substr(0, 5) + '\n' + '...';
      }
      return str;
    }
  }
};
</script>

<style scoped>
.current {
  width: 60px;
  height: 28px;
  background: #f4f4f5;
  line-height: 28px;
  text-align: center;
  color: #18181b;
  border-radius: 6px;
}
.left_right_btn {
  width: 28px;
  height: 28px;
  color: #18181b;
}
.date {
  width: 100%;
  height: 28px;
  line-height: 28px;
  text-align: center;
  color: #333333;
  font-size: 18px;
  font-weight: 500;
  cursor: pointer;
  vertical-align: middle;
}
.type {
  width: 46px;
  height: 28px;
  border-radius: 8px;
  cursor: pointer;
  padding: 4px 16px;
  color: #71717a;
  line-height: 20px;
}
.type_active {
  background: #1990ff;
  color: #ffffff;
}
.timetable_month {
  width: 100%;
  float: left;
}
.timetable_month .weekdays,.days {
  display: flex;
}
.timetable_month li{
  flex: 1;
  list-style-type:none;
  width: 14.2%;
  height: 84px;
  border-bottom: 1px solid #dfe6ec;
  padding: 12px 10px;
  cursor: pointer;
  color: #000;
  font-weight: 500;
}
.timetable_month .days li {
  height: 124px;
  overflow: hidden;
}
.timetable_month li:first-child, li:last-child{
  background: #fafafa;
}
.timetable_month li:not(:first-child){
  border-left: 1px solid #dfe6ec;
}
.timetable_month .weekdays li p:first-child{
  font-size: 12px;
  line-height: 12px;
  font-weight: 500;
  color: #71717a;
}
.timetable_month .weekdays li p:last-child{
  font-size: 22px;
  line-height: 32px;
  font-weight: 500;
  color: #000;
}
.timetable_month .days li{
  text-align: center;
  padding: 2px 2px;
}
.timetable_month .active {
  display: inline-block;
  width: 20px;
  height: 20px;
  line-height: 20px;
  border-radius: 50%;
  overflow: hidden;
  background: #1990ff;
  color: #ffffff;
  font-weight: 600;
}
.timetable_month .no_active {
  display: inline-block;
  width: 20px;
  height: 20px;
  line-height: 20px;
  border-radius: 50%;
  overflow: hidden;
}
.other_month {
  font-size: 12px;
  font-weight: 400;
  color: #dcdfe6;
}
.bottom_box {
  width: 100%;
  height: 100%;
  text-align: left;
  display: flex;
  flex-wrap: nowrap;
}
.class_td {
  height: 96px;
  padding: 4px;
  color: #ffffff;
  vertical-align: top;
  line-height: 14px;
  box-sizing: border-box;
  border-radius: 4px;
  border: 1px solid #ffffff;
  overflow: hidden;
  word-break: break-all;
}
.ellipsis {
  height: 84px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 6;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
}
/* .selected{

} */
.class_name {
  height: 28px;
  line-height: 28px;
  color: #1990ff;
  font-size: 16px;
  font-weight: 600;
  vertical-align: middle;
}
</style>
